package com.wx.task.future;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;



/**
 * 批量异步任务
 * 需求：
 *      从三个电商平台 对同一个商品进行价格获取
 *      将每个价格保存入库
 *      比较三个报价最小值
 *
 *
 * CompletionService 内部存在队列用于保存future
 * @author wang.xun
 * @date 2023/08/03
 */
@Slf4j
public class CompletionServiceTest {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        CompletionService<Integer> cs = new ExecutorCompletionService<>(threadPool);

        cs.submit(CompletionServiceTest::getPrice1);
        cs.submit(CompletionServiceTest::getPrice2);
        cs.submit(CompletionServiceTest::getPrice3);

        ExecutorService dbThreadPool = Executors.newFixedThreadPool(3);


        // 获取队列值，进行入库和比价
        AtomicInteger atomicInteger = new AtomicInteger(Integer.MAX_VALUE);
        CountDownLatch countDownLatch = new CountDownLatch(3);
        while (countDownLatch.getCount() > 0){
            //log.info("countDownLatch :{}", countDownLatch.getCount());
            try {
                final Integer price = cs.take().get();
                // 异步入库
                dbThreadPool.submit(() -> {
                    saveDB(price);
                });
                // 比较出最小值
                int min = Integer.min(price, atomicInteger.get());
                log.info("{} 与 {} 比较小的是: {}",price,atomicInteger.get(),min);
                atomicInteger.set(min);
                countDownLatch.countDown();


            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }

        log.info("所有平台最便宜的价格是：{}元", atomicInteger.get());
        dbThreadPool.shutdown();
        threadPool.shutdown();



    }

    private static void saveDB(Integer price) {
        log.info("入库 ：{}",price);
    }

    private static Integer getPrice1() {
        int price = RandomUtil.randomInt(5000);
        log.info("平台1的价格 ：{}",price);
        return price;
    }
    private static Integer getPrice2() {

        int price = RandomUtil.randomInt(5000);
        log.info("平台2的价格 ：{}",price);
        return price;
    }
    private static Integer getPrice3() {

        int price = RandomUtil.randomInt(5000);
        log.info("平台3的价格 ：{}",price);
        return price;
    }
}
